//
//  AppDelegate.m
//  618
//
//  Created by Jacky.Chen on 13-6-20.
//  Copyright __618工作室__ 2013年. All rights reserved.
//

#import "cocos2d.h"

#import "AppDelegate.h"
#import "IntroLayer.h"
#import "SourceLog.h"
#import "SourceChecks.h"
#import "GameScene.h"
#import "TopScoreViewController.h"


@implementation AppController

@synthesize window=window_, navController=navController_, director=director_;
@synthesize notifyCenter,gs,highScoresViewController;

+ (AppController *)sharedAppDelegate
{
    // This can fail at app launch when instantiated via MainWindow.nib:
    //   - Instantiation order is not guaranteed. View controllers have been observed to be instantiated first.
    //   - Connection order is not guaranteed. Connections are only made after everything has been instantiated.
    // This means:
    //   - Instantiation in -initWithCoder: will not work.
    //   - Instantiation in -viewDidLoad and -view{Will,Did}Appear: will not work if the nib sets UIWindow.rootViewController
    //   - Instantiation in -awakeFromNib work provided it is called (e.g. it might not be called for objects instantiated not via -initWithCoder:)
    return ASAssertStaticCast(AppController, [[UIApplication sharedApplication] delegate]);
}




- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
	
    //使用消息来响应点击操作，切换场景
    self.notifyCenter = [NSNotificationCenter defaultCenter];
	[notifyCenter addObserver:self selector:@selector(trackNotifications:) name:nil object:nil];
    
    // Create the main window
	window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    
	// Create an CCGLView with a RGB565 color buffer, and a depth buffer of 0-bits
	CCGLView *glView = [CCGLView viewWithFrame:[window_ bounds]
								   pixelFormat:kEAGLColorFormatRGB565	//kEAGLColorFormatRGBA8
								   depthFormat:0	//GL_DEPTH_COMPONENT24_OES
							preserveBackbuffer:NO
									sharegroup:nil
								 multiSampling:NO
							   numberOfSamples:0];

	director_ = (CCDirectorIOS*) [CCDirector sharedDirector];

	director_.wantsFullScreenLayout = YES;

	// Display FSP and SPF
//	[director_ setDisplayStats:YES];

	// set FPS at 60
	[director_ setAnimationInterval:1.0/60];

	// attach the openglView to the director
	[director_ setView:glView];

	// for rotation and other messages
	[director_ setDelegate:self];

	// 2D projection
	[director_ setProjection:kCCDirectorProjection2D];
//	[director setProjection:kCCDirectorProjection3D];

	// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
	if( ! [director_ enableRetinaDisplay:YES] )
		CCLOG(@"Retina Display Not supported");

	// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
	// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
	// You can change anytime.
	[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];

	// If the 1st suffix is not found and if fallback is enabled then fallback suffixes are going to searched. If none is found, it will try with the name without suffix.
	// On iPad HD  : "-ipadhd", "-ipad",  "-hd"
	// On iPad     : "-ipad", "-hd"
	// On iPhone HD: "-hd"
	CCFileUtils *sharedFileUtils = [CCFileUtils sharedFileUtils];
	[sharedFileUtils setEnableFallbackSuffixes:NO];				// Default: NO. No fallback suffixes are going to be used
	[sharedFileUtils setiPhoneRetinaDisplaySuffix:@"-hd"];		// Default on iPhone RetinaDisplay is "-hd"
	[sharedFileUtils setiPadSuffix:@"-ipad"];					// Default on iPad is "ipad"
	[sharedFileUtils setiPadRetinaDisplaySuffix:@"-ipadhd"];	// Default on iPad RetinaDisplay is "-ipadhd"

	// Assume that PVR images have premultiplied alpha
	[CCTexture2D PVRImagesHavePremultipliedAlpha:YES];

	// and add the scene to the stack. The director will run it when it automatically when the view is displayed.
	//显示游戏场景
    //GameScene *gs = [GameScene node];
    self.gs =  [GameScene node];
    [director_ pushScene: gs];
    //[director_ pushScene: [IntroLayer scene]];
    
	
	// Create a Navigation Controller with the Director
	navController_ = [[UINavigationController alloc] initWithRootViewController:director_];
	navController_.navigationBar.barStyle = UIBarStyleBlackOpaque;
    navController_.navigationBarHidden = YES;
	
	// set the Navigation Controller as the root view controller
//	[window_ addSubview:navController_.view];	// Generates flicker.
	[window_ setRootViewController:navController_];
	
	// make main window visible
	[window_ makeKeyAndVisible];
	
	return YES;
}

// Supported orientations: Landscape. Customize it for your own needs
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return UIInterfaceOrientationIsPortrait(interfaceOrientation);
}


// getting a call, pause the game
-(void) applicationWillResignActive:(UIApplication *)application
{
	if( [navController_ visibleViewController] == director_ )
		[director_ pause];
}

// call got rejected
-(void) applicationDidBecomeActive:(UIApplication *)application
{
	if( [navController_ visibleViewController] == director_ )
		[director_ resume];
}

-(void) applicationDidEnterBackground:(UIApplication*)application
{
	[self.gs saveGames];
    if( [navController_ visibleViewController] == director_ )
		[director_ stopAnimation];
}

-(void) applicationWillEnterForeground:(UIApplication*)application
{
	if( [navController_ visibleViewController] == director_ )
		[director_ startAnimation];
}

// application will be killed
- (void)applicationWillTerminate:(UIApplication *)application
{
	[self.gs saveGames];
    CC_DIRECTOR_END();
}

// purge memory
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
	[[CCDirector sharedDirector] purgeCachedData];
}

// next delta time will be zero
-(void) applicationSignificantTimeChange:(UIApplication *)application
{
	[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}

- (void) dealloc
{
	[window_ release];
	[navController_ release];
    [notifyCenter release];
    self.gs = nil;
	[super dealloc];
}
#pragma mark <get notification when selector menu>

- (void) trackNotifications: (NSNotification *) notification
{
	id nname = [notification name];
    //Log_Debug(@"notification name = %@",nname);
    
    if([nname isEqual:@"highScores"])
	{
       // TopScoreViewController
        Log_Debug(@"英雄榜");
        TopScoreViewController *high = [[TopScoreViewController alloc] init];
        self.highScoresViewController = high;
        CGSize size = [[CCDirector sharedDirector] winSize];
        CGRect sizes = high.view.frame;
        sizes = CGRectMake(0, 0, size.width, size.height);
        high.view.frame = sizes;
		[self showUIViewController:high];
        [high release];
    }
    if([nname isEqual:@"continueGames"])
	{
        Log_Debug(@"继续游戏");
    }
    if([nname isEqual:@"about"])
	{
        Log_Debug(@"关于我们");
    }
    if([nname isEqual:@"removeHighScores"])
	{
		[self hideUIViewController:highScoresViewController];
		
		[highScoresViewController release];
		highScoresViewController = nil;
	}
    
}
#pragma mark <change Scene>

- (void) showUIViewController:(UIViewController *) controller
{
//	[director_ pause];
	[director_ stopAnimation];
    
    
    
//	[UIView beginAnimations:nil context:NULL];
//	[UIView setAnimationDuration:.5];
//	[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:[director_ view] cache:YES];
//	navController_.navigationBarHidden = NO;
//    director_.title = @"英雄榜";
//    [[director_ view] addSubview:controller.view];
//	UIBarButtonItem* cancelBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain
//                                                                     target:self action:@selector(hideUIViewController)];
//    //cancelBtnItem.image = cancelImg;
//    director_.navigationItem.leftBarButtonItem = cancelBtnItem;
//    [cancelBtnItem release];
//	[UIView commitAnimations];
    
    navController_.navigationBarHidden = NO;
    director_.title = @"英雄榜";
    [navController_  pushViewController:controller animated:YES];
}

- (void) hideUIViewController:(UIViewController *) controller
{
	[director_ startAnimation];
    //[director_ resume];
    
    [UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.5];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(animDone:finished:context:)];
	
	[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:[director_ view] cache:YES];
	navController_.navigationBarHidden = YES;
	[controller.view removeFromSuperview];
	[UIView commitAnimations];
        
}
- (void) hideUIViewController
{
	[director_ startAnimation];
//    [director_ resume];
    
    [UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.5];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(animDone:finished:context:)];
	
	[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:[director_ view] cache:YES];
	navController_.navigationBarHidden = YES;
	[highScoresViewController.view removeFromSuperview];
	[highScoresViewController release];
    highScoresViewController = nil;
	[UIView commitAnimations];
    
}
@end

